<template>
  <view class="my-trades-page">
    <!-- 自定义导航栏 -->
    <nav-bar title="我的闲置" :show-back="true"></nav-bar>
    
    <!-- 闲置分类切换 -->
    <view class="tab-switch">
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        全部
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'sell' }"
        @click="switchTab('sell')"
      >
        我的出售
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'buy' }"
        @click="switchTab('buy')"
      >
        我的求购
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'sold' }"
        @click="switchTab('sold')"
      >
        已完成
      </view>
    </view>
    
    <!-- 闲置列表 -->
    <scroll-view 
      class="trade-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="filteredTrades.length > 0" class="trades-container">
        <view 
          v-for="trade in filteredTrades" 
          :key="trade.id"
          class="trade-item"
          @click="viewTradeDetail(trade)"
        >
          <image class="trade-image" :src="trade.coverImage" mode="aspectFill"></image>
          
          <view class="trade-content">
            <view class="trade-top">
              <view class="trade-type" :class="trade.idleType">
                {{ trade.idleType === 'sell' ? '出售' : '求购' }}
              </view>
              <view class="trade-status" :class="trade.status">
                {{ getStatusText(trade.status) }}
              </view>
            </view>
            
            <view class="trade-title">{{ trade.title }}</view>
            
            <view class="trade-price">
              <text class="price-symbol">¥</text>
              <text class="price-value">{{ trade.price }}</text>
            </view>
            
            <view class="trade-bottom">
              <view class="trade-time">{{ formatTime(trade.createTime) }}</view>
              <view class="trade-actions">
                <view 
                  class="action-edit" 
                  @click.stop="editTrade(trade)"
                  v-if="trade.status !== 'completed'"
                >
                  编辑
                </view>
                <view class="action-divider"></view>
                <view 
                  class="action-delete" 
                  @click.stop="confirmDelete(trade)"
                >
                  删除
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty-trade.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无闲置物品</text>
        <view class="action-buttons">
          <button class="action-btn sell-btn" @click="createSell">发布闲置</button>
          <button class="action-btn buy-btn" @click="createBuy">发布求购</button>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore && filteredTrades.length > 0">
        <tn-loading mode="circle" size="24"></tn-loading>
        <text>加载更多...</text>
      </view>
      
      <view class="no-more" v-if="!hasMore && filteredTrades.length > 0">
        <text>没有更多闲置了</text>
      </view>
    </scroll-view>
    
    <!-- 悬浮按钮 -->
    <view class="float-buttons">
      <view class="float-btn" @click="createSell">
        <view class="btn-icon sell-icon">
          <tn-icon name="plus" size="32" color="#FFFFFF"></tn-icon>
        </view>
        <text>发布闲置</text>
      </view>
      <view class="float-btn" @click="createBuy">
        <view class="btn-icon buy-icon">
          <tn-icon name="search" size="32" color="#FFFFFF"></tn-icon>
        </view>
        <text>发布求购</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/navbar/NavBar.vue';

// 当前选中的标签
const activeTab = ref('all');

// 闲置列表
const trades = ref([]);
const isRefreshing = ref(false);
const hasMore = ref(true);

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
};

// 过滤闲置
const filteredTrades = computed(() => {
  if (activeTab.value === 'all') {
    return trades.value;
  }
  
  if (activeTab.value === 'sell') {
    return trades.value.filter(trade => trade.idleType === 'sell' && trade.status !== 'completed');
  }
  
  if (activeTab.value === 'buy') {
    return trades.value.filter(trade => trade.idleType === 'buy' && trade.status !== 'completed');
  }
  
  if (activeTab.value === 'sold') {
    return trades.value.filter(trade => trade.status === 'completed');
  }
  
  return trades.value;
});

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'published': '已发布',
    'pending': '审核中',
    'completed': '已完成',
    'closed': '已下架'
  };
  return statusMap[status] || status;
};

// 时间格式化
const formatTime = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  
  // 计算时间差（毫秒）
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前';
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
  }
  
  // 大于30天显示具体日期
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 查看闲置详情
const viewTradeDetail = (trade) => {
  uni.navigateTo({
    url: `/pages/detail/idle-detail?id=${trade.id}`
  });
};

// 编辑闲置
const editTrade = (trade) => {
  uni.navigateTo({
    url: `/pages/publish/idle?id=${trade.id}&type=${trade.idleType}&edit=true`
  });
};

// 发布出售
const createSell = () => {
  uni.navigateTo({
    url: '/pages/publish/idle?type=sell'
  });
};

// 发布求购
const createBuy = () => {
  uni.navigateTo({
    url: '/pages/publish/idle?type=buy'
  });
};

// 确认删除
const confirmDelete = (trade) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个闲置物品吗？删除后无法恢复',
    confirmColor: '#FF5252',
    success: (res) => {
      if (res.confirm) {
        deleteTrade(trade);
      }
    }
  });
};

// 删除闲置
const deleteTrade = (trade) => {
  // 实际项目中应该调用API删除闲置
  const index = trades.value.findIndex(item => item.id === trade.id);
  if (index !== -1) {
    trades.value.splice(index, 1);
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    });
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value) return;
  
  console.log('加载更多闲置');
  
  // 实际项目中应该调用API加载更多闲置
  // 模拟加载
  setTimeout(() => {
    if (trades.value.length >= 20) {
      hasMore.value = false;
      return;
    }
    
    // 模拟新数据
    const newTrades = generateMockTrades(trades.value.length + 1, 5);
    trades.value = [...trades.value, ...newTrades];
  }, 1000);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  
  // 实际项目中应该调用API刷新闲置列表
  console.log('刷新闲置列表');
  
  // 模拟刷新完成
  setTimeout(() => {
    isRefreshing.value = false;
    
    // 重置数据
    initTrades();
  }, 1000);
};

// 生成模拟闲置数据
const generateMockTrades = (startId, count) => {
  const result = [];
  const types = ['sell', 'buy'];
  const statuses = ['published', 'pending', 'completed', 'closed'];
  
  for (let i = 0; i < count; i++) {
    const id = startId + i;
    const idleType = types[Math.floor(Math.random() * types.length)];
    const imgId = 100 + Math.floor(Math.random() * 100);
    
    result.push({
      id,
      title: idleType === 'sell' ? 
        `出售：9成新 ${['iPhone', 'iPad', 'MacBook', '华为手机', '小米平板'][i % 5]} ${id}` : 
        `求购：${['教材书', '自行车', '二手电脑', '计算器', '健身器材'][i % 5]} ${id}`,
      description: `这是一个${idleType === 'sell' ? '出售' : '求购'}物品的详情描述，包含物品信息、新旧程度、交易方式等。`,
      coverImage: `https://picsum.photos/id/${imgId}/300/300`,
      images: [`https://picsum.photos/id/${imgId}/300/300`],
      price: idleType === 'sell' ? (200 + Math.floor(Math.random() * 5000)) : (100 + Math.floor(Math.random() * 1000)),
      idleType,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      createTime: new Date(new Date().getTime() - id * 3600000 * (Math.random() * 24))
    });
  }
  
  return result;
};

// 初始化闲置列表
const initTrades = () => {
  trades.value = generateMockTrades(1, 10);
  hasMore.value = true;
};

onMounted(() => {
  // 初始化闲置列表
  initTrades();
});
</script>

<style lang="scss" scoped>
.my-trades-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 180rpx;
}

.tab-switch {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 2;
  
  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
    font-size: 28rpx;
    color: #666666;
    position: relative;
    
    &.active {
      color: #32C5FF;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #32C5FF;
        border-radius: 4rpx;
      }
    }
  }
}

.trade-list {
  padding: 20rpx;
}

.trades-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.trade-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  display: flex;
  
  .trade-image {
    width: 220rpx;
    height: 220rpx;
    flex-shrink: 0;
  }
  
  .trade-content {
    flex: 1;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    position: relative;
  }
  
  .trade-top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16rpx;
    
    .trade-type {
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      font-size: 20rpx;
      text-align: center;
      
      &.sell {
        background-color: rgba(50, 197, 255, 0.1);
        color: #32C5FF;
      }
      
      &.buy {
        background-color: rgba(186, 104, 200, 0.1);
        color: #BA68C8;
      }
    }
    
    .trade-status {
      font-size: 20rpx;
      color: #999999;
      
      &.completed {
        color: #4CAF50;
      }
      
      &.closed {
        color: #9E9E9E;
      }
    }
  }
  
  .trade-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 16rpx;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .trade-price {
    color: #FF5252;
    margin-bottom: 16rpx;
    
    .price-symbol {
      font-size: 24rpx;
    }
    
    .price-value {
      font-size: 34rpx;
      font-weight: bold;
    }
  }
  
  .trade-bottom {
    margin-top: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .trade-time {
      font-size: 22rpx;
      color: #999999;
    }
    
    .trade-actions {
      display: flex;
      align-items: center;
      
      .action-edit, .action-delete {
        font-size: 24rpx;
        padding: 0 10rpx;
      }
      
      .action-edit {
        color: #32C5FF;
      }
      
      .action-delete {
        color: #FF5252;
      }
      
      .action-divider {
        width: 1rpx;
        height: 24rpx;
        background-color: #e0e0e0;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 250rpx;
    height: 250rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    
    .action-btn {
      width: 220rpx;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
      color: #FFFFFF;
      
      &::after {
        border: none;
      }
    }
    
    .sell-btn {
      background: linear-gradient(135deg, #32C5FF, #2196F3);
    }
    
    .buy-btn {
      background: linear-gradient(135deg, #BA68C8, #9C27B0);
    }
  }
}

.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #999999;
  
  text {
    margin-left: 10rpx;
  }
}

.float-buttons {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  
  .float-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .btn-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
    }
    
    .sell-icon {
      background: linear-gradient(135deg, #32C5FF, #2196F3);
    }
    
    .buy-icon {
      background: linear-gradient(135deg, #BA68C8, #9C27B0);
    }
    
    text {
      font-size: 22rpx;
      color: #666666;
      background-color: #FFFFFF;
      padding: 4rpx 10rpx;
      border-radius: 10rpx;
    }
  }
}
</style> 